#pragma once

#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <thread>
#include <mutex>

int count3 = 100;

void *thread3(void *argv, std::mutex &mymutex2)
{
    while (1)
    {
        mymutex2.lock();
        if (count3 > 0)
        {
            usleep(1000);
            std::cout << "child thread tid: " << (char *)argv << " my count = " << count3 << std::endl;
            count3--;
            mymutex2.unlock();
        }
        else
        {
            return nullptr;
        }
    }
    return nullptr;
}

// cpp加锁
void cpp_mutex_local()
{
    std::mutex mymutex2;
    std::thread pth1(thread3, (void *)"thread1", std::ref(mymutex2));
    std::thread pth2(thread3, (void *)"thread2", std::ref(mymutex2));
    std::thread pth3(thread3, (void *)"thread3", std::ref(mymutex2));
    std::thread pth4(thread3, (void *)"thread4", std::ref(mymutex2));
    std::thread pth5(thread3, (void *)"thread5", std::ref(mymutex2));

    pth1.detach();
    pth2.detach();
    pth3.detach();
    pth4.detach();
    pth5.detach();

    while (count3 > 0)
    {
        usleep(1000);
    }
    usleep(2000);
}
